﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class Inventory : MonoBehaviour {

	private RectTransform inventoryRect;

	private float inventoryWidth, inventoryHight;

	public int slots;                        // 背包总共多少个格

	public int rows;                         // 背包有几行

	public float slotPaddingLeft,slotPaddingTop;   // 背包每格距离左边上边多少距离

	public float slotSize;                   // 背包小格边长

	public GameObject slotPrefab; 

	private static  Slot from, to;   //todo 为什么改static了

	private List<GameObject> allSlots;

	public GameObject iconPrefab; 

	private static GameObject hoverObject;

	private static int emptySlots;

	public Canvas canvas;

	private float hoverYOffset;   // 在点击挪动物体的时候，右下角跟图标有问题，所以引入这个变量来解决

	public EventSystem eventSystem;

	public static  int EmptySlots{
		get{ return emptySlots; }
		set{ emptySlots = value; }
	}



	// Use this for initialization
	void Start () {
		CreateLayout ();
	}
	
	// Update is called once per frame
	void Update () {

		// 如果是把物品挪到外面去了，就删掉物品，代码还要再看，具体还没理解
		if (Input.GetMouseButtonUp(0)) {
			if (!eventSystem.IsPointerOverGameObject(-1) && from != null) {
				from.GetComponent<Image> ().color = Color.white;
				from.ClearSlot ();
				Destroy (GameObject.Find ("Hover"));
				to = null;
				from = null;
				hoverObject = null;
			}
		}

		if (hoverObject != null) {
			Vector2 position;
			RectTransformUtility.ScreenPointToLocalPointInRectangle (
				canvas.transform as RectTransform, Input.mousePosition, canvas.worldCamera, out position);

			position.Set (position.x, position.y - hoverYOffset);

			hoverObject.transform.position = canvas.transform.TransformPoint (position);	
		}
	}

	private void CreateLayout(){

		allSlots = new List<GameObject> ();

		hoverYOffset = slotSize * 0.01f;

		emptySlots = slots;

		// 下面是 计算及显示 包裹外层大小
		// 关于下面的计算公式，搞不懂可以看笔记 ，这个其实就是计算占用长宽
		inventoryWidth = (slots / rows) * (slotSize + slotPaddingLeft) + slotPaddingLeft;
		inventoryHight = rows * (slotSize + slotPaddingTop) + slotPaddingTop;

		inventoryRect = GetComponent<RectTransform>();

		inventoryRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Horizontal, inventoryWidth);   //todo 这个6 !!!, 是什么意思 ？？？ 
		inventoryRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical, inventoryHight);   // 这个6 !!!

		// 下面就是关于 背包内部具体绘制了
		int columns = slots / rows;
		for (int y = 0; y < rows; y++) {
			for (int x = 0; x < columns; x++) {
				GameObject newSlot = (GameObject)Instantiate (slotPrefab);
				RectTransform slotRect = newSlot.GetComponent<RectTransform> ();
				newSlot.name = "Slot";
				newSlot.transform.SetParent (this.transform.parent);

				// 这是绘制每个背包格的最核心代码
				slotRect.localPosition = inventoryRect.localPosition + new Vector3 (
					slotPaddingLeft * (x + 1) + (slotSize * x),
					-slotPaddingTop * (y + 1) - (slotSize * y));

				slotRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Horizontal, slotSize);
				slotRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical, slotSize);

				allSlots.Add (newSlot);  
			}
		}
		// 到这里背包样式雏形就出来了
	}


	public bool AddItem (Item item){
		if (item.maxSize == 1) {
			PlaceEmpty (item);
			return true;
		}else {
			foreach (GameObject slot in allSlots) {

				Slot tmp = slot.GetComponent<Slot> ();

				if (!tmp.IsEmpty) {
					if (tmp.CurrentItem.type == item.type && tmp.IsAvailable) {
						tmp.AddItem (item);
						emptySlots--;    // Do not write this line of code! We only want to reduce the number of slots when we place an item on an empty slot
						return true;
					}
				}
			}
			if (emptySlots > 0 ) {
				PlaceEmpty (item);
			}
		}

		return false;
	}


	private bool PlaceEmpty(Item item){
		if (emptySlots > 0) {
			foreach (GameObject slot in allSlots) {
				Slot tmp = slot.GetComponent<Slot> ();

				if (tmp.IsEmpty) {
					tmp.AddItem (item);
					emptySlots--;
					return true;
				}
			}
		}
		return false;
	}

	public void MoveItem(GameObject clicked){
		if (from == null) {
			if (!clicked.GetComponent<Slot>().IsEmpty) {
				from = clicked.GetComponent<Slot> ();
				from.GetComponent<Image> ().color = Color.gray;

				hoverObject = (GameObject) Instantiate (iconPrefab);
				hoverObject.GetComponent<Image> ().sprite = clicked.GetComponent<Image> ().sprite;
				hoverObject.name = "Hover";

				RectTransform hoverTransform = hoverObject.GetComponent<RectTransform> ();
				RectTransform clickedTranform = clicked.GetComponent<RectTransform> ();

				hoverTransform.SetSizeWithCurrentAnchors (RectTransform.Axis.Horizontal, clickedTranform.sizeDelta.x);
				hoverTransform.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical, clickedTranform.sizeDelta.y);

				hoverObject.transform.SetParent (GameObject.Find ("Canvas").transform, true);
				hoverObject.transform.localScale = from.gameObject.transform.localScale;
			}
		}else if (to == null) {
			to = clicked.GetComponent<Slot> ();

			Destroy (GameObject.Find ("Hover"));      // 这个用于删除多余的挪动残影
		}

		if (to != null && from != null) {
			Stack<Item> tmpTo = new Stack<Item> (to.Items);
			to.AddItems (from.Items);

			if (tmpTo.Count == 0) {
				from.ClearSlot ();
			} else {
				from.AddItems (tmpTo);
			}

			from.GetComponent<Image> ().color = Color.white;
			to = null;
			from = null;
			hoverObject = null;
		}
	}
}
